package com.yonyou.print.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.yonyou.dao.entity.BOVO;
import com.yonyou.dao.entity.TemplateVO;
import com.yonyou.print.params.ParamsEngine;
import com.yonyou.service.CloudPrintService;
import com.yonyou.service.PrintDBService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.yonyou.print.params.Constant;
import com.yonyou.service.HttpService;
import org.springframework.stereotype.Controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 云打印接口
 * <p>
 * BO:业务对象
 */
@Controller
public class PrintManageCtrl {
    @Autowired
    private PrintDBService printDBService;
    @Autowired
    private CloudPrintService cloudPrintService;
    @Autowired
    private HttpService httpService;

    @RequestMapping(value = {"/"}, method = RequestMethod.GET)
    public String start() {
        if (printDBService.connectDB()) {
            return "template";
        }
        return "printInit";
    }

    @RequestMapping(value = {"/setting"}, method = RequestMethod.GET)
    public String setting() {
        return "printInit";
    }

    @RequestMapping(value = {"/template"}, method = RequestMethod.GET)
    public String template() {
        return "template";
    }

    @RequestMapping(value = "testDB", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    @ResponseBody
    public String testDB(@RequestParam("mysqlUrl") String mysqlUrl, @RequestParam("mysqlName") String mysqlName,
                         @RequestParam("mysqlPassword") String mysqlPassword, @RequestParam("mysqlUser") String mysqlUser) {
        String url = "jdbc:mysql://" + mysqlUrl + "/" + mysqlName + "?useUnicode=true&amp;characterEncoding=utf8";
        JSONObject result = new JSONObject();
        int connection = printDBService.connectDB(mysqlUrl, mysqlName, mysqlUser, mysqlPassword);
        result.put("connection", connection);
        switch (connection) {
            case -1: {
                break;
            }
            case 1: {
                result.put("result", "success");
                return result.toString();
            }
            case 2: {
                result.put("result", "created");
                result.put("message", "创建数据库成功，请保存配置后重启服务生效");
                return result.toString();
            }
        }
        result.put("result", "failure");
        result.put("message", "数据库连接失败");
        return result.toString();
    }

    //保存BO，BO格式请看BO_TagPrint.txt文件
    @RequestMapping(value = {"/saveBO"}, method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public JSONObject saveBO(@RequestParam("boStr") String boStr) {
        Map<String, String> param = new HashMap<String, String>();
        JSONObject obj = new JSONObject();
        try {
            JSONObject boJSON = JSONObject.parseObject(boStr).getJSONObject("bo");
            if (boJSON == null || !(boJSON instanceof JSONObject) ||
                    !boJSON.containsKey("bo_code") || !boJSON.containsKey("bo_name")) {
                obj.put("saveResult", "BO格式不正确！");
                return obj;
            }

            param.put("boStr", boStr);
            // TODO 这里发版的时候需要放开
            Object result = httpService.httpPostRequest(Constant.saveBOUrl, param);
            obj = JSONObject.parseObject(result.toString());
            // 如果保存成功
            if (obj.get("saveResult").equals("true")) {
                obj.put("params", Constant.formBOInfo(boJSON));
            }
        } catch (JSONException exception) {
            obj.put("saveResult", "业务对象格式不正确！");
            return obj;
        }
        return obj;
    }

    /**
     * 更新BO，实际上是用新的BO内容替换原来的BO，切记上传完整BO
     */
    @RequestMapping(value = "/updateBO", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object updateBO(@RequestParam("boStr") String boStr) {
        Map<String, String> param = new HashMap<String, String>();
        param.put("boStr", boStr);
        JSONObject obj = new JSONObject();
        JSONObject boJSON = JSONObject.parseObject(boStr).getJSONObject("bo");
        if (boJSON == null || !(boJSON instanceof JSONObject) ||
                !boJSON.containsKey("bo_code") || !boJSON.containsKey("bo_name")) {
            obj.put("updateResult", "BO格式不正确！");
            return obj;
        }
        String bo_code = boJSON.getString("bo_code");

        List<BOVO> bos = printDBService.findBO(bo_code);

        param.put("pk_bo", bos.get(0).getPk_bo());

        Object result = httpService.httpPostRequest(Constant.upaateBOUrl, param);
        obj = JSONObject.parseObject(result.toString());
        if (obj.getBoolean("updateResult")) {
            obj.put("params", Constant.formBOInfo(boJSON));
        }
        return obj;
    }

    /**
     * 复制模板后，保存模板信息到本地数据库
     */
    @RequestMapping(value = {"/copyTemByPk"}, method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String copyTemByPk(@RequestParam("pk_print_template") String pk_print_template,
                              @RequestParam("copytemplatecode") String copytemplatecode,
                              @RequestParam("copytemplatename") String copytemplatename) {
        Map<String, String> param = new HashMap<String, String>();
        param.put("pk_template", pk_print_template);
        param.put("templatecode", copytemplatecode);
        param.put("templatename", copytemplatename);
        //云端复制
        String result = cloudPrintService.copyCloudTemplate(param);

        //同步到本地
        return result;
    }

    /**
     * 删除模板（模板管理界面使用）
     */
    @RequestMapping(value = {"/deleteTemplate"}, method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String deleteTemplate(@RequestParam("pk_print_template") String pk_print_template) {
        Map<String, String> param = new HashMap<String, String>();
        param.put("pk_template", pk_print_template);
        JSONObject resultObj = JSONObject.parseObject(cloudPrintService.deleteCloudTemplate(param).toString());
        if (resultObj.containsKey("delresult") && resultObj.getBoolean("delresult")) {
            //本地数据库删除模板
            if (printDBService.deleteTemplate(pk_print_template) > 0) {
                return resultObj.toString();
            }
        }
        return "Delete Failed";
    }


    /**
     * 从本地数据库查询所有BO和BO下的所有模板
     * 模板管理用
     */
    @RequestMapping(value = {"/querybo"}, method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String getLocalBOTemp() {
        JSONArray templates = (JSONArray) JSONArray.toJSON(printDBService.getAllTemplates(""));
        JSONObject result = new JSONObject();
        result.put("templates", templates);
        //本地配置参数添加到返回结果
        String print_token = ParamsEngine.getInfoConfig().getProperty("print_token");
        String tenantId = ParamsEngine.getInfoConfig().getProperty("tenantId");
        String serviceUrl = ParamsEngine.getInfoConfig().getProperty("serviceUrl");
        result.put("print_token", print_token);
        result.put("tenantId", tenantId);
        result.put("serviceUrl", serviceUrl);
        return result.toString();
    }

    @RequestMapping(value = "/templatePreview", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String templatePreview(@RequestParam("params") Object params) {
        JSONObject result = new JSONObject();
        try {
            JSONObject paramJSON = JSONObject.parseObject(params.toString());
            JSONArray data = paramJSON.getJSONArray("printData");
            String bo_code = paramJSON.getString("boCode");
            result.put(bo_code, data);
        } catch (JSONException exception) {
            result.put("saveResult", "业务对象格式不正确！");
            return result.toString();
        }
        return result.toString();
    }

    /**
     * 保存本地配置
     *
     * @param print_token
     * @param tenantId
     * @param mysqlUrl
     * @return
     */
    @RequestMapping(value = {"/saveConfig"}, method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String saveConfig(@RequestParam("print_token") String print_token, @RequestParam("tenantId") String tenantId,
                             @RequestParam("mysqlUrl") String mysqlUrl, @RequestParam("mysqlName") String mysqlName,
                             @RequestParam("mysqlPassword") String mysqlPassword, @RequestParam("serviceUrl") String serviceUrl,
                             @RequestParam("mysqlUser") String mysqlUser) {
        //测试数据库连接
        JSONObject result =new JSONObject();
        //保存配置
        Map<String,String> params = new HashMap<String, String>();
        params.put("print_token",print_token);
        params.put("tenantId",tenantId);
        params.put("jdbc.mysql.url",mysqlUrl);
        params.put("jdbc.mysql.name",mysqlName);
        params.put("jdbc.mysql.username",mysqlUser);
        params.put("jdbc.mysql.password",mysqlPassword);
        params.put("serviceUrl",serviceUrl);
        ParamsEngine.saveProperty(params);

        result.put("result", "success");
        return result.toString();
    }

    /**
     * 加载本地配置
     *
     * @return
     */
    @RequestMapping(value = {"/loadConfig"}, method = RequestMethod.GET)
    @ResponseBody
    public String loadConfig() {
        JSONObject obj = new JSONObject();
        obj.put("print_token", ParamsEngine.getInfoConfig().getProperty("print_token"));
        obj.put("tenantId", ParamsEngine.getInfoConfig().getProperty("tenantId"));
        obj.put("mysqlUrl", ParamsEngine.getInfoConfig().getProperty("jdbc.mysql.url"));
        obj.put("mysqlName", ParamsEngine.getInfoConfig().getProperty("jdbc.mysql.name"));
        obj.put("mysqlUser", ParamsEngine.getInfoConfig().getProperty("jdbc.mysql.username"));
        obj.put("mysqlPassword", ParamsEngine.getInfoConfig().getProperty("jdbc.mysql.password"));
        obj.put("serviceUrl", ParamsEngine.getInfoConfig().getProperty("serviceUrl"));
        obj.put("data", "success");
        return obj.toString();
    }

    /**
     * 从云端同步数据持久化到本地。
     *
     * @param type
     * @return
     */
    @RequestMapping(value = "initBOAndTemplate", method = RequestMethod.POST)
    @ResponseBody
    public String initBOAndTemplate(
            @RequestParam(value = "type", required = true, defaultValue = "0") int type) {
        printDBService.init();
//        printDBService.saveBO(cloudPrintService.getCloudBOs());
        //查询BO
        List<BOVO> bos = cloudPrintService.getCloudBOs();

        //查询打印模板
        List<TemplateVO> templateVOList = cloudPrintService.getCloudTemplates();
//        printDBService.saveTemplates(templateVOList);
        //同步
        List<String> changeTemplateCodes = printDBService.syncAllTemplates(bos, templateVOList);

        Map<String, String> boPKCode = new HashMap<String, String>();
        for (int i = 0; i < bos.size(); i++) {
            BOVO bo = bos.get(i);
            boPKCode.put(bo.getPk_bo(), bo.getBo_code());
        }

        //查询打印模板模型
        JSONArray bo_template = new JSONArray();
        for (int i = 0; i < templateVOList.size(); i++) {
            String templateCode = templateVOList.get(i).getTemplatecode();
            if (changeTemplateCodes.contains(templateCode)) {
                com.alibaba.fastjson.JSONObject tempInfo = new com.alibaba.fastjson.JSONObject();
                tempInfo.put("templateCode", templateCode);
                tempInfo.put("bo_code", boPKCode.get(templateVOList.get(i).getPk_bo()));
                tempInfo.put("pk_print_template", templateVOList.get(i).getPk_print_template());
                bo_template.add(tempInfo);
            }
        }
        //保存打印模板模型
        if (bo_template.size() > 0) {
            printDBService.saveTemplateItems(cloudPrintService.getPrintModel(bo_template));
        }
        JSONObject result = new JSONObject();
        result.put("result", "success");
        return result.toString();
    }
}
